package com.morgan.basemodule.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import java.io.File

/**
 *description：
 *<br>author：caowugao
 *<br>time：2021/4/21 0021 16:33
 */
class IntentUtils private constructor(){
    companion object {

        fun setIntentDataAndType(
            context: Context,
            intent: Intent,
            type: String?,
            file: File,
            endAuthorities: String,
            writeAble: Boolean
        ) = FileProviderCompat.setIntentDataAndType(context, intent, type, file, endAuthorities, writeAble)

        /**
         *
         * <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
         */
        fun installApk(context : Context, filePath : String, endAuthorities: String) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (context.packageManager.canRequestPackageInstalls()) {
                    realInstallApk(filePath, context, endAuthorities)
                    return
                }
                try {
                    val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + context.packageName))
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    context.startActivity(intent)
                } catch (e : Throwable) {
                    e.printStackTrace()
                }
                return
            }
            realInstallApk(filePath, context, endAuthorities)
        }

        private fun realInstallApk(
            filePath: String,
            context: Context,
            endAuthorities: String
        ) {
            val f = File(filePath)
            val intent = Intent(Intent.ACTION_VIEW)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            setIntentDataAndType(
                context,
                intent,
                "application/vnd.android.package-archive",
                f,
                endAuthorities,
                false
            )
            try {
                context.startActivity(intent)
            } catch (e: Throwable) {
                e.printStackTrace()
            }
        }
    }
}